package utils

import (
	"fmt"
	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/ebitenutil"
	_ "image/gif"
	"log"
)

func GetCoordination() (X, Y float64) {
	// 获取坐标
	x, y := ebiten.CursorPosition()
	X = float64(x)
	Y = float64(y)
	//fmt.Println(x, y)
	return X, Y
}

func CalculatePlantCardCoordination(PlantCardSlice []string, Images map[string]*ebiten.Image) map[string]struct {
	Top    float64
	Bottom float64
	Right  float64
	Left   float64
} {
	// 计算植物坐标
	var PlantCardCoordination = make(map[string]struct {
		Top    float64
		Bottom float64
		Right  float64
		Left   float64
	})
	var distance = 87.0
	for i := 0; i < len(PlantCardSlice); i++ {
		op := &ebiten.DrawImageOptions{}
		name := PlantCardSlice[i]
		distance = distance + 4
		op.GeoM.Scale(0.82, 0.82)
		op.GeoM.Translate(distance, 5.4)
		if _, ok := Images[name]; ok {
			cardWidth, cardHeight := Images[name].Size()
			cardWidth = int(float64(cardWidth) * 0.82)
			cardHeight = int(float64(cardHeight) * 0.82)
			PlantCardCoordination[name] = struct {
				Top    float64
				Bottom float64
				Right  float64
				Left   float64
			}{
				Top:    op.GeoM.Element(1, 2),
				Bottom: op.GeoM.Element(1, 2) + float64(cardHeight),
				Right:  op.GeoM.Element(0, 2) + float64(cardWidth),
				Left:   op.GeoM.Element(0, 2),
			}
		}
		distance = distance + 52

	}
	return PlantCardCoordination
}

func GetClickedPlantCard(PlantCardCoordination map[string]struct {
	Top    float64
	Bottom float64
	Right  float64
	Left   float64
}) (name string) {
	// 判断是否在坐标里面,
	name = ""
	x, y := GetCoordination()
	var (
		top    float64
		bottom float64
		right  float64
		left   float64
	)
	for i, value := range PlantCardCoordination {
		top = value.Top
		bottom = value.Bottom
		right = value.Right
		left = value.Left
		if x > left && x < right && y > top && y < bottom {
			// 判断是那颗植物
			name = i
			//fmt.Println(i)
			return i
		}
	}
	return name
}

func MouseBindPlantSource(s string) *ebiten.Image {
	// 返回图片地址
	img, _, err := ebitenutil.NewImageFromFile("")
	img = nil
	if err != nil {
		fmt.Println("加载植物卡片--ing")
	}
	if s == "peashooter" {
		img, _, err = ebitenutil.NewImageFromFile("PlantsVsZombies1/image/Plants/Peashooter/Peashooter/frame_0.Png")
		if err != nil {

		}
	} else if s == "sunFlower" {
		img, _, err = ebitenutil.NewImageFromFile("PlantsVsZombies1/image/Plants/SunFlower/SunFlower/frame_0.Png")
		if err != nil {
			log.Fatal(err)
		}
	} else if s == "nutWall" {
		img, _, err = ebitenutil.NewImageFromFile("PlantsVsZombies1/image/Plants/WallNut/WallNut.gif")
		if img == nil {
		}
		if err != nil {
			log.Fatal(err)
		}
	} else if s == "cherryBomb" {
		img, _, err = ebitenutil.NewImageFromFile("PlantsVsZombies1/image/Plants/CherryBomb/CherryBomb/frame_0.Png")
		if err != nil {
			log.Fatal(err)
		}
	}
	return img
}
